import '@umijs/max';
import React, { useEffect, useState } from 'react';
import { useParams } from '@@/exports';
import {
  chartRetryUsingPost,
  getChartByIdUsingGet,
  updateChartUsingPost,
} from '@/services/api/chartController';
import { Button, Card, Col, Divider, Input, message, Row, Space } from 'antd';
import { ProColumns, ProFormRadio } from '@ant-design/pro-components';
import { DataSourceItemType } from 'antd/lib/auto-complete';
import { EditableProTable } from '@ant-design/pro-components';
import ChartErrorBoundary from '@/pages/Bi/Components/ChartErrorBoundary';
import EChartsReact from 'echarts-for-react';

/**
 * 图表详情页面
 *
 * @constructor
 */
const ChartDataPage: React.FC = () => {
  const [loading, setLoading] = useState<boolean>(false);
  const { chartId } = useParams();
  const [position, setPosition] = useState<'top' | 'bottom' | 'hidden'>('bottom');

  const [maxIdx, setMaxIdx] = useState<number>(0);
  const [chartEditVO, setChartEditVO] = useState<API.ChartEditVO>({});
  // 新增或修改的表单
  const [chartDataFormIds, setChartDataFormIds] = useState<number[]>([]);

  /**
   * 构建列
   */
  const buildColumns = () => {
    const chartOriginalData = chartEditVO.chartOriginalData;
    const headers = chartOriginalData?.headers;
    const columns: ProColumns<DataSourceItemType>[] = new Array();
    if (headers) {
      for (let i = 0; i < headers.length; i++) {
        const header = headers[i];
        const column = {
          title: header,
          dataIndex: header,
          formItemProps: {
            rules: [
              {
                required: true,
                whitespace: true,
                message: '此项是必填项',
              },
            ],
          },
        };
        columns.push(column);
      }
    }
    columns.push({
      title: '操作',
      valueType: 'option',
      width: 200,
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            //@ts-ignore
            action?.startEditable?.(record?.idx);
          }}
        >
          编辑
        </a>,
      ],
    });
    return columns;
  };

  /**
   * 加载数据
   */
  const loadData = async () => {
    if (chartId === null) return;
    setLoading(true);
    try {
      const res = await getChartByIdUsingGet({ id: chartId as any });
      if (res.data) {
        setChartEditVO(res.data);
        // setDataSource(chartEditVO.chartOriginalData?.rows);
        chartEditVO.chartOriginalData?.rows?.forEach((item) => {
          const v = item['idx'] as number;
          setMaxIdx(Math.max(v, maxIdx));
        });
      } else {
        message.success('数据不存在');
      }
    } catch (e) {}

    setLoading(false);
  };

  /**
   * 修改 或 添加列表数据事件
   * @param rowKey
   * @param data
   */
  const saveChartDataHandle = (rowKey: any, data: object) => {
    chartEditVO.chartOriginalData?.rows?.push(data);
    if (!chartDataFormIds.includes(rowKey)) {
      chartDataFormIds.push(rowKey);
    }
  };

  /**
   * 图表保存
   */
  const submitUpdate = async () => {
    setLoading(true);
    const oldChartData = chartEditVO.chartOriginalData;
    const rows: object[] = [];

    // 原始数据表修改 & 新增
    if (chartDataFormIds.length) {
      const headers = oldChartData?.headers ?? [];

      oldChartData?.rows?.forEach((current) => {
        if (chartDataFormIds.includes(current.idx)) {
          const row = {};
          for (let i = 0; i < headers?.length; i++) {
            let key = headers[i];
            // 修改
            if (key === 'idx' && current.idx > maxIdx) {
            } else {
              //添加
              // @ts-ignore
              row[key] = current[key];
            }
          }
          rows.push(row);
        }
      });
    }

    const params = {
      id: chartEditVO.chart?.id,
      name: chartEditVO.chart?.name,
      genChart: chartEditVO.chart?.genChart,
      chartOriginalData: {
        headers: oldChartData?.headers,
        rows: rows,
      },
    } as API.ChartUpdateRequest;

    try {
      const res = await updateChartUsingPost(params);

      if (res.data) {
        loadData();
        message.success('操作成功');
      } else {
        message.error('操作失败');
      }
    } catch (e) {}

    setLoading(false);
  };



  /**
   * option
   * @param e
   */
  const handleChartEditVOChange = (e: any) => {
    setChartEditVO({
      ...chartEditVO,
      chart: {
        ...chartEditVO.chart,
        genChart: e.target.value,
      },
    });
  };

  const getOption = () => {
    try {
      return JSON.parse(chartEditVO.chart?.genChart || '{}');
    } catch (e) {
      message.error('option error');
    }
    return {};
  };
  /**
   * 自动加载数据
   */
  useEffect(() => {
    loadData();
  }, [chartId]);

  /**
   *重新生成图表
   */
  const chartRetryHandle = async () => {
    if (!chartEditVO.chart?.id) return;
    try {
      const res = await chartRetryUsingPost({ id: chartEditVO.chart?.id });
      if (res.data) {
        history.back();
        message.success('正在重新分析数据 请等待. . .');
      } else {
        message.error('重试失败');
      }
    } catch (e) {}
  };

  return (
    <div className="chart-data-detail-page">
      <Row
        gutter={{
          xs: 1,
          sm: 1,
          md: 2,
          lg: 2,
          xl: 3,
        }}
      >
        <Col xs={24} sm={24} md={24} lg={24} xl={24} style={{ marginBottom: 3 }}>
          <Card
            title={'图表详情'}
            extra={
              <Space>
                <Button
                  onClick={() => {
                    history.back();
                  }}
                >
                  返回
                </Button>
                <Button danger onClick={() => chartRetryHandle()}>
                  再次分析
                </Button>
              </Space>
            }
          >
            <div>{'图表名称：' + chartEditVO.chart?.name}</div>
            <Divider />
            <div>{'分析目标：' + chartEditVO.chart?.goal}</div>
          </Card>
        </Col>
        <Col xs={24} sm={24} md={12} lg={12} xl={12}>
          <Card
            title={'图表配置'}
            extra={
              <Space>
                <Button onClick={() => loadData()}>重置</Button>
                <Button
                  type="primary"
                  onClick={() => {
                    setChartDataFormIds([]);
                    submitUpdate();
                  }}
                >
                  保存配置
                </Button>
              </Space>
            }
          >
            <Input.TextArea
              showCount
              style={{ height: 520 }}
              value={chartEditVO.chart?.genChart}
              onChange={(e) => handleChartEditVOChange(e)}
            />
          </Card>
        </Col>
        <Col xs={24} sm={24} md={12} lg={12} xl={12}>
          <Card title={'图表'}>
            <div>
              <ChartErrorBoundary>
                <EChartsReact option={getOption()} style={{ height: 520 }} />
              </ChartErrorBoundary>
            </div>
          </Card>
        </Col>
        <Col xs={24} sm={24} md={24} lg={24} xl={24} style={{ marginTop: 3 }}>
          <Card title={'原始数据列表'} extra={<Button onClick={() => submitUpdate()}>保存</Button>}>
            <EditableProTable<any>
              rowKey="idx"
              headerTitle="可编辑表格"
              maxLength={100}
              scroll={{
                x: 960,
              }}
              recordCreatorProps={
                position !== 'hidden'
                  ? {
                      position: position as 'top',
                      record: () => ({ idx: (Math.random() * 1000000).toFixed(0) }),
                    }
                  : false
              }
              loading={loading}
              toolBarRender={() => [
                <ProFormRadio.Group
                  key="render"
                  fieldProps={{
                    value: position,
                    onChange: (e) => setPosition(e.target.value),
                  }}
                  options={[
                    {
                      label: '添加到顶部',
                      value: 'top',
                    },
                    {
                      label: '添加到底部',
                      value: 'bottom',
                    },
                    {
                      label: '隐藏',
                      value: 'hidden',
                    },
                  ]}
                />,
              ]}
              columns={buildColumns()}
              request={async () => ({
                data: chartEditVO.chartOriginalData?.rows,
                total: chartEditVO.chartOriginalData?.rows?.length,
                success: true,
              })}
              value={chartEditVO.chartOriginalData?.rows}
              onChange={() => {
                console.log('222');
              }}
              editable={{
                type: 'single',
                onSave: async (rowKey, data) => {
                  saveChartDataHandle(rowKey, data);
                },
                onChange: (rowKey, row) => {
                  console.log('onChange:', rowKey, row);
                },
              }}
            />
          </Card>
        </Col>
      </Row>
    </div>
  );
};
export default ChartDataPage;
